package com.example.tvrecyclerviewkotlin.view

import android.content.Context
import android.util.AttributeSet
import android.view.FocusFinder
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView


/**
 *@author: njb
 *@date:  2021/2/1 12:41
 *@desc:
 */
class FocusRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {


    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        if (event.action === KeyEvent.ACTION_DOWN) {
            val keyCode: Int = event.keyCode
            // 这里只考虑水平移动的情况（垂直移动相同的解决方案）
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                val focusedView: View = focusedChild // 获取当前获得焦点的view
                val nextFocusView: View?
                nextFocusView = try {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                        // 通过findNextFocus获取下一个需要得到焦点的view
                        FocusFinder.getInstance()
                            .findNextFocus(this, focusedView, View.FOCUS_LEFT)
                    } else {
                        // 通过findNextFocus获取下一个需要得到焦点的view
                        FocusFinder.getInstance()
                            .findNextFocus(this, focusedView, View.FOCUS_RIGHT)
                    }
                } catch (e: Exception) {
                    null
                }
                // 如果获取失败（也就是说需要交给系统来处理焦点， 消耗掉事件，不让系统处理， 并让先前获取焦点的view获取焦点）
                if (nextFocusView == null) {
                    focusedView.requestFocus()
                    return true
                }
            }
        }
        return super.dispatchKeyEvent(event)
    }

}